Page({
  data: {
    passport: {},
    nUrl: ''
  },
  onLoad({ id ,encryptedData}) {
    this.getPassport(id)
    this.getPassportShare(encryptedData)
  },
  // 获取访客接口
  async getPassport(id) {
    // 检测是否存在 id
    if (!id) return
    const res = await wx.http.get(`/visitor/${id}`)
    console.log(res);
    this.setData({
      passport: res.data,
      nUrl: res.data.url
    })
  },
  async getPassportShare(encryptedData) {
    // 检测是否存在 id
    if (!encryptedData) return
    // 调用接口
    const { data: passport } = await wx.http.get('/visitor/share/' + encryptedData)
    // 检测接口是否调用成功
    // 渲染数据
    this.setData({ passport })
  },
  // 分享给朋友触发事件onShareAppMessage
  onShareAppMessage() {
    // 获取加密数据
    const { encryptedData } = this.data.passport
    return {
      title: '查看通行证',
      path: '/visitor_pkg/pages/passport/index?encryptedData=' + encryptedData,
      imageUrl: 'https://enjoy-plus.oss-cn-beijing.aliyuncs.com/images/share_poster.png',
    }
  },
  // 小程序授权检测
  authSetting() {
    wx.getSetting({
      success: ({ authSetting }) => {
        if (authSetting['scope.writePhotosAlbum'] === false) {
          // 如果拒绝授权
          wx.showModal({
            // title: '',
            content: '请允许添加到相册',
            showCancel: false,
            success: () => {
              // 打开设置
              wx.openSetting({
                success: ({ authSetting }) => {
                  // 同意授权
                  if (authSetting['scope.writePhotosAlbum'] === true) {
                    // 调用添加图片
                    this.savePhoto()
                  }
                }
              })
            }
          })
        } else {
          this.savePhoto()
        }
      }
    })
  },
  // 保存图片到本地
  async savePhoto() {
    try {
      const res = await wx.getImageInfo({
        src: this.data.nUrl,
      })
      // console.log(res);
      await wx.saveImageToPhotosAlbum({
        filePath: res.path,
      })
      wx.utils.toast('保存图片成功')
    } catch (err) {

    }
  },
  onShareAppMessage() {
    return {
      title: '查看通行证',
      path: '/visitor_pkg/pages/passport/index',
      imageUrl: 'https://enjoy-plus.oss-cn-beijing.aliyuncs.com/images/share_poster.png',
    }
  },
})
